﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utils;
using System.Text.RegularExpressions;
using PanasonicWarranty.Business;
using Settings;

namespace PanasonicWarranty.UI
{
    public partial class ChangePassword : BasePage
    {
        protected override bool HasRole()
        {
            return true;
        }

        protected override bool RequiredChangePassword()
        {
            return false;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CurrentPassword.Focus();
            }
        }

        protected void CancelPushButton_Click(object sender, EventArgs e)
        {
            if (CurUser.RequiredChangePassword == false)
                RedirectToPage(DefaultURL);
        }

        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            using (var context = new DBSysDataContext(AppSetting.ConnectionString))
            {
                var curUser = context.SysUsers.FirstOrDefault(p => p.UserID == UserID);
                if (curUser == null)
                {
                    RedirectToPage(LoginURL);
                }
                if (!curUser.Password.Equals(CurrentPassword.Text.Trim().ToMD5Hash(), StringComparison.CurrentCultureIgnoreCase))
                {
                    ShowMessageBox("Mật khẩu cũ không chính xác");
                    return;
                }
                if (!Regex.IsMatch(NewPassword.Text.Trim(), @"(?=.*\d)(?=.*[a-zA-Z]).{6,50}"))
                {
                    ShowMessageBox("Mật khẩu phải có chữ và số, dài trong khoảng 6-50 ký tự");
                    return;
                }
                curUser.Password = NewPassword.Text.Trim().ToMD5Hash();
                curUser.RequiredChangePassword = false;
                context.SubmitChanges();
                RegisterStartUpScript(string.Format("ChangePasswordSucsess('{0}')", ResolveUrl(DefaultURL)));
            }
        }
    }
}
